package com.micro.boot.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.micro.boot.exception.CustomGenericException;

/**
 * 
 * @Description: 异常处理器
 * @param     
 * @throws
 * @author renweiping
  *@e_mail renweiping_1113@google.com
 * @date 2018年9月18日
 */
@RestControllerAdvice
public class SysExceptionHandler extends ResponseEntityExceptionHandler {


	 	@ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类，会自动映射
	    public Map<String,Object> customGenericExceptionHnadler(CustomGenericException exception){ //还可以声明接收其他任意参数
	 		Map<String,Object> errorMap = new HashMap<String,Object>();
	        errorMap.put("errCode", exception.getErrCode());
	        errorMap.put("errMsg", exception.getErrMsg());
	        return errorMap;
	    }

	    @ExceptionHandler(Exception.class)//可以直接写@EceptionHandler，IOExeption继承于Exception
	    public Map<String,Object> allExceptionHandler(HttpServletRequest request,Exception exception){
	 		Map<String,Object> errorMap = new HashMap<String,Object>();
	        errorMap.put("errCode", getStatus(request));
	        errorMap.put("errMsg", exception.getMessage());
	        return errorMap;
	    }
	
	    
	    
		private HttpStatus getStatus(HttpServletRequest request) {
			Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
			if (statusCode == null) {
				return HttpStatus.INTERNAL_SERVER_ERROR;
			}
			return HttpStatus.valueOf(statusCode);
		}
}
